// WebSocket.js
class WebSocketService {
	constructor(url) {
		this.socket = null;
		this.url = url;
		this.callbacks = {};
	}

	// 连接WebSocket
	connect(url) {
		this.socket = new WebSocket(url);

		this.socket.onopen = () => {
			console.log('WebSocket连接已建立:', url);
			if (this.callbacks['open']) {
				this.callbacks['open']();
			}
		};

		this.socket.onmessage = (event) => {
			console.log('收到消息:event.data', event);
			let data = {}
			try {
				data = JSON.parse(event.data);
			} catch (error) {
				//TODO handle the exception
			}
			console.log('收到消息:', data);
			if (this.callbacks['message']) {
				this.callbacks['message'](data);
			}
		};

		this.socket.onclose = () => {
			console.log('WebSocket连接已关闭');
			if (this.callbacks['close']) {
				this.callbacks['close']();
			}
		};

		this.socket.onerror = (error) => {
			console.error('WebSocket发生错误:', error);
			if (this.callbacks['error']) {
				this.callbacks['error'](error);
			}
		};
	}

	// 发送消息
	send(message) {
		if (this.socket && this.socket.readyState === WebSocket.OPEN) {
			if (typeof message == 'string') {
				this.socket.send(message);
			} else {
				this.socket.send(JSON.stringify(message));
			}
			console.log('发送消息:', message);
		} else {
			console.error('WebSocket未连接，无法发送消息');
		}
	}

	// 注册回调函数
	on(event, callback) {
		this.callbacks[event] = callback;
	}

	// 关闭WebSocket连接
	close() {
		if (this.socket) {
			this.socket.close();
		}
	}
}

export default WebSocketService;